package com.softme.trade.control;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.primefaces.event.TabChangeEvent;
import org.primefaces.event.TabCloseEvent;

import com.softme.trade.view.util.FacesUtil;

/**
 * Essa classe faz o controle das tabs que o sistema apresentará para o usuário
 * Possui @SessionScoped para manter o objeto na sessão enquanto logado.
 * 
 * @author Mews
 * 
 */
@SessionScoped
@ManagedBean
public class TabViewController
{
	private List<TabItem> tabList;
	private int activeIndex = 0;

	//dados que vão para a tab
	private String label;
	private String url;
	private String tabID;

	public String getLabel()
	{
		return label;
	}

	public void setLabel(String label)
	{
		this.label = label;

	}

	public String getTabID()
	{
		return tabID;
	}

	public void setTabID(String tabID)
	{
		this.tabID = tabID;

		//Depois de passados todos os parâmetros do menu para a TAB
		//pode adicionar a tab
		this.addTab();
	}

	public String getUrl()
	{
		return url;
	}

	public void setUrl(String url)
	{
		this.url = url;
	}

	public TabViewController()
	{
		tabList = new ArrayList<TabItem>();

		//sempre terá a tab HOME
		tabList.add(new TabItem("Home", "home.xhtml", 0, false, "home"));
	}

	public void addTab()
	{
		//verifica se a tab já existe em tela para não permitir que duplique
		//TODO verificar se o cliente precisa de mais de uma tab para um mesmo cadastro
		int tabIndex = this.getTabIndexFrom(this.tabID);
		
		if (tabIndex < 0)
		{
			tabIndex = tabList.size();

			this.tabList.add(new TabItem(this.label, this.url, tabIndex, true, this.tabID));
		}

		this.setActiveIndex(tabIndex);
		
//		FacesUtil.refreshCurrentPage();
	}

	private int getTabIndexFrom(String id)
	{
		for (TabItem tab : this.tabList)
		{
			if (tab.id.equals(id))
				return this.tabList.indexOf(tab);
		}

		return -1;
	}

	public List<TabItem> getTabList()
	{
		return tabList;
	}

	public void setTabList(List<TabItem> tabList)
	{
		this.tabList = tabList;
	}

	public int getActiveIndex()
	{
		return activeIndex;
	}

	public void setActiveIndex(int activeIndex)
	{
		this.activeIndex = activeIndex;
	}

	public void onTabClose(TabCloseEvent event)
	{
		getTabList().remove(this.getIndexFromCurrentTab());
	}

	public void onTabChange(TabChangeEvent event)
	{
		this.setActiveIndex(this.getIndexFromCurrentTab());
	}

	private int getIndexFromCurrentTab()
	{
		ExternalContext external = FacesContext.getCurrentInstance().getExternalContext();
		Map<String, String> requestMap = external.getRequestParameterMap();

		//***********************************************
		//TODO - PRECISA MELHORAR POR CAUSA DO DESEMPENHO
		//***********************************************

		//procura entre todos os parâmetros o tabIndex da tab corrente
		for (String code : requestMap.keySet())
		{
			if (code.contains("tabindex"))
				return Integer.parseInt(requestMap.get(code));
		}

		return -1;
	}

	@SessionScoped
	public class TabItem
	{
		private String title;
		private String url;
		private int tabIndex;
		private boolean closeable;
		private String id;

		//TODO assim que necessário colocar mais atributos nessa tab

		public TabItem(String title, String url, int tabIndex, boolean closeable, String id)
		{
			this.setTitle(title);
			this.setUrl(url);
			this.setTabIndex(tabIndex);
			this.setCloseable(closeable);
			this.setId(id);
		}

		public String getTitle()
		{
			return title;
		}

		public void setTitle(String title)
		{
			this.title = title;
		}

		public String getId()
		{
			return id;
		}

		public void setId(String id)
		{
			this.id = id;
		}

		public String getUrl()
		{
			return url;
		}

		public void setUrl(String url)
		{
			this.url = url;
		}

		public int getTabIndex()
		{
			return tabIndex;
		}

		public void setTabIndex(int tabIndex)
		{
			this.tabIndex = tabIndex;
		}

		public boolean isCloseable()
		{
			return closeable;
		}

		public void setCloseable(boolean closeable)
		{
			this.closeable = closeable;
		}
	}
}
